var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http, { cors: true });





var arrAllSocket = {};
io.on("connection", function (socket) {
  // 加入聊天室
  socket.on('join', function (data) {
    user = data.userName;
    arrAllSocket[user] = socket;//把socket存到全局数组里面去
    console.log('加入房间')

  });

  //私聊：服务器接受到私聊信息，发送给目标用户
  socket.on('private_message', function (data) {
    let to = data.to
    let from = data.from
    var target = arrAllSocket[to]; //接收目标
    var sendtarget = arrAllSocket[from]   //发出目标
    console.log(target, 'ssssss')
    // 接受方实列存在
    if (target) {
      target.emit("pmsg", data);
    } else {
      // 发方实例存在
      if(sendtarget){
        sendtarget.emit("sysmsg", { 
          type: 'syc',
          msg:'对方离开'
        });
      }
    }
  });

  // 监听私聊消息
  socket.on('pmsg', function (data) {
    alert("get private message...from:" + data);
  });

  socket.on('delSocket', function (data) {
    if(arrAllSocket[data]){
      delete arrAllSocket[data]
      console.log(data, '离开...',arrAllSocket)
    }
  })

  socket.on('disconnect', function (data) {
    console.log('断开连接')
  })

});




http.listen(5000, function () {
  console.log("链接上了服务器5000");
});









